const router = require('koa-router')()
const Person = require('../dbs/models/person')

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

router.get('/addPerson', async function(ctx) {
  const person = new Person({name: 'xubin', age: 18})
  let code
  try {
    await person.save()
    code = 0
  } catch (e) {
    code = -1
  }
  ctx.body = {
    code: code
  }
})
router.get('/getPerson', async function(ctx) {
  const result = await Person.findOne({name: 'xubin'}) // 找到一个就不在找了
  const results = await Person.find({name: 'xubin'})
  ctx.body = {
    code: 0,
    result,
    results
  }
})
router.get('/updatePerson',async function(ctx){
  const result = await Person.where({ // 改一个
    name: 'xubin'
  }).update({
    age: 19
  })
  ctx.body={
    code:0
  }
})

router.get('/removePerson',async function(ctx){
  const result = await Person.where({  // 删全部
    name: 'xubin'
  }).remove()

  ctx.body={
    code:0
  }
})


module.exports = router
